package com.musiklegal;

import android.app.Activity;
import android.app.ProgressDialog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.security.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.math.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.app.Dialog;


import android.content.Context;

import android.content.SharedPreferences;

import android.telephony.TelephonyManager;

import android.widget.EditText;


public class Facebook extends Activity 
{
	String uid;
	ProgressDialog dialog;
	
	public void onResume()
    {
    	super.onResume();
    	if(!MusikLegal.internet(this))
   	 {
   		 
   		 finish();
   	 }
    }
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
    	if(!MusikLegal.internet(getApplicationContext()))
    		finish();
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.fb);
        
        
        uid = MusikLegal.getUID(getApplicationContext());
        Button logfb = (Button) this.findViewById(R.id.logfb);
        logfb.setOnClickListener(new OnClickListener() {
    		public void onClick(View arg0) {
    			tryLogin();
		}
	});
     }
    
    void tryLogin()
    {
    	EditText etxt_pass = (EditText) findViewById(R.id.passfb);
		EditText etxt_user = (EditText) findViewById(R.id.userfb);
		
		String password = etxt_pass.getText().toString();
		String username = etxt_user.getText().toString();
		
		try {
			password = generatePass(password);
		} catch (NoSuchAlgorithmException e) {
			
			e.printStackTrace();
		}
   
        
        	DefaultHttpClient client = new DefaultHttpClient();
        	HttpGet get = new HttpGet("musiklegal.com/fbauth.php?source=mobile&touch=1");
        	try {  
        		
	        	  HttpResponse response = client.execute(get);

	        	  HttpEntity responseEntity = response.getEntity();
	        	  SAXParserFactory spf = SAXParserFactory.newInstance();
	        	  SAXParser sp = spf.newSAXParser();
	        	  XMLReader xr = sp.getXMLReader();
			
	        	  LoginHandler loginHand = new LoginHandler();
	        	  xr.setContentHandler(loginHand);
	        	  xr.parse(retrieveInputStream(responseEntity));
			
	        	  ParsedLoginDataSet fbset = loginHand.getParsedLoginData();
	        	  if (fbset.getExtractedString().equals("success")) 
	              {
	 				 	showDialog(0);
	 				 	HttpPost contact = new HttpPost("http://secure.musiklegal.com/app_contact/contact");
	 			        HttpPost subs = new HttpPost("http://secure.musiklegal.com/subscription/check");
	 			        List< BasicNameValuePair > nvcs = new ArrayList< BasicNameValuePair >();
	 			        List< BasicNameValuePair > nvss = new ArrayList< BasicNameValuePair >();
	 			        nvcs.add(new BasicNameValuePair("USERNAME", username));
	 			        nvcs.add(new BasicNameValuePair("UID", uid));
	 			        nvss.add(new BasicNameValuePair("USERNAME", username));
	 			        nvss.add(new BasicNameValuePair("UID", uid));
	 			        
	 			        try {

	 			        	  
	 			        	  UrlEncodedFormEntity c_entity = new UrlEncodedFormEntity(nvcs,HTTP.UTF_8);
	 			        	  UrlEncodedFormEntity s_entity = new UrlEncodedFormEntity(nvss,HTTP.UTF_8);
	 			        	  
	 			        	  
	 			        	  contact.setEntity(c_entity);
	 			        	  subs.setEntity(s_entity);
	 			        	  
	 			            
	 			              HttpResponse response2 = client.execute(contact);
	 			              HttpResponse response3 = client.execute(subs);
	 			              
	 			              
	 			              HttpEntity responseEntity2 = response2.getEntity();
	 			              HttpEntity responseEntity3 = response3.getEntity();
	 			              
	 			              LoginHandler contHand = new LoginHandler();
	 			              LoginHandler subsHand = new LoginHandler();
	 			              
	 			              
	 			              xr.setContentHandler(contHand);
	 			              xr.setContentHandler(subsHand);
	 			              
	 			              
	 			              xr.parse(retrieveInputStream(responseEntity2));
	 			              xr.parse(retrieveInputStream(responseEntity3));
	 			              
	 			              
	 			              ParsedLoginDataSet subset = subsHand.getParsedLoginData();
	 			                
	 			              SharedPreferences.Editor editor=MusikLegal.mPreferences.edit();
	 		                    editor.putString("UserName", username);
	 		                    editor.putString("PassWord", password);
	 		                    
	 		                    if(subset.getSiD()!=null)
	 		                    {
	 		                    	editor.putString("SubId", subset.getSiD());
	 		                    	MusikLegal.on = true;
	 		                    }
	 		                    if(subset.getDate()!=null)
	 		                    {
	 		                    	editor.putString("SubDate", subset.getDate());
	 		                    }
	 		                    editor.commit();         
	 		                    startActivity(new Intent(getApplicationContext(), MainMenu.class));
	 		                    finish();
	 			        }
	 			        catch (Exception e)
	 			        {
	 			        	
	 			            
	 			        }
	 			        
	                    
	              }
	 			 else Toast.makeText(getApplicationContext(), "Wrong Username or Password",
	                      Toast.LENGTH_SHORT).show();
        	}
        	 catch (Exception e)
		        {
		        	
		            
		        }
        	 
			 
        
  }
    
    public String generatePass(String pass) throws NoSuchAlgorithmException
    {
    	MessageDigest m = MessageDigest.getInstance("MD5");
		byte[] data = pass.getBytes(); 
		m.update(data,0,data.length);
		BigInteger i = new BigInteger(1,m.digest());
		String str = String.format("%1$032X", i);
		return str.toLowerCase();
    }
    protected Dialog onCreateDialog(int id) {
        switch (id) {
              case 0: {
                    dialog = new ProgressDialog(this);
                    dialog.setMessage("Redirecting...");
                    dialog.setIndeterminate(true);
                    dialog.setCancelable(true);
                    return dialog;                   
              }
        }
        return null;
  }
    private InputSource retrieveInputStream(HttpEntity httpEntity) {
        InputSource insrc = null;
        try {
              insrc = new InputSource(httpEntity.getContent());
        } catch (Exception e) {
        }
        return insrc;
  } 
}

